import { useRoleStore } from "@/stores/role";
import type { Category, PolicyRule, Role } from "@halo-dev/api-client";
import { coreApiClient } from "@halo-dev/api-client";
import { useQuery } from "@tanstack/vue-query";
import type { Ref } from "vue";
import { ref } from "vue";
import type { CategoryTree } from "../utils";
import { buildCategoriesTree } from "../utils";

interface usePostCategoryReturn {
  categories: Ref<Category[] | undefined>;
  categoriesTree: Ref<CategoryTree[]>;
  isLoading: Ref<boolean>;
  handleFetchCategories: () => void;
}

export function usePostCategory(): usePostCategoryReturn {
  const categoriesTree = ref<CategoryTree[]>([] as CategoryTree[]);

  const {
    data: categories,
    isLoading,
    refetch,
  } = useQuery({
    queryKey: ["post-categories"],
    queryFn: async () => {
      const { data } = await coreApiClient.content.category.listCategory({
        page: 0,
        size: 0,
        sort: ["metadata.creationTimestamp,desc"],
      });

      return data.items;
    },
    refetchInterval(data) {
      const hasAbnormalCategory = data?.some(
        (category) =>
          !!category.metadata.deletionTimestamp || !category.status?.permalink
      );
      return hasAbnormalCategory ? 1000 : false;
    },
    onSuccess(data) {
      const roleStore = useRoleStore();
      const { roles } = roleStore.permissions;

      //找到该用户 关于分类的所有权限
      const categoriesPermissions = roles
        .map((role: Role) => {
          return role.rules.filter(
            (rule: PolicyRule) =>
              (rule.apiGroups &&
                rule.apiGroups.some(
                  (apiGroup: string) =>
                    apiGroup === "content.halo.run" &&
                    rule.resources &&
                    rule.resources.some(
                      (source: string) =>
                        source === "categories" || source === "*"
                    )
                )) ||
              (rule.apiGroups &&
                rule.apiGroups.some(
                  (apiGroup: string) =>
                    apiGroup === "*" &&
                    rule.apiGroups &&
                    rule.apiGroups.some((apiGroup: string) => apiGroup === "*")
                ))
          );
        })
        .flat();
      categoriesTree.value = buildCategoriesTree(data, categoriesPermissions);
    },
  });

  return {
    categories,
    categoriesTree,
    isLoading,
    handleFetchCategories: refetch,
  };
}

interface useCategorySelectionReturn {
  selectedCategories: Ref<Array<string>>;
  handleCategoriesSelect: (e: Event) => void;
  hadPostMange: (selectedRoleTemplates: Set<string>) => boolean;
}
/**
 * Logic for selecting category templates
 *
 * @returns {useCategorySelectionReturn}
 */
export function useCategorySelection(
  categories: Ref<Category[] | undefined>
): useCategorySelectionReturn {
  const selectedCategories = ref<Array<string>>([]);
  const handleCategoriesSelect = async (e: Event) => {
    const { checked, value } = e.target as HTMLInputElement;
    if (!checked) {
      return;
    }
    const category = categories.value?.find(
      (role) => role.metadata.name === value
    );

    if (!category) {
      return;
    }

    // selectedCategories.value.push(category.metadata.name);
    // resolveDeepDependencies(category, categories.value || []).forEach((name) => {
    //   selectedCategories.value.add(name);
    // });
  };
  const hadPostMange = (selectedTemplates: Set<string>): boolean => {
    return selectedTemplates.has("role-template-manage-posts");
  };

  return {
    selectedCategories,
    handleCategoriesSelect,
    hadPostMange,
  };
}
